package org.jeecg.common.config;

import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 多租户信息存储器
 * @author: jeecg-boot
 */
public class TenantContext {
    private static final Logger logger = LoggerFactory.getLogger(TenantContext.class);
    private static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<>();

    /**
     * 设置租户ID
     * @param tenant 租户ID
     */
    public static void setTenant(String tenant) {
        if (logger.isDebugEnabled()) {
            logger.debug("设置租户ID: {}", tenant);
        }
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<>();
            threadLocal.set(map);
        }
        map.put("tenantId", tenant);
    }

    /**
     * 获取租户ID
     * @return 租户ID
     */
    public static String getTenant() {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            return null;
        }
        return (String) map.get("tenantId");
    }

    /**
     * 设置线程变量
     * @param key 键
     * @param value 值
     */
    public static void set(String key, Object value) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<>();
            threadLocal.set(map);
        }
        map.put(key, value);
    }

    /**
     * 获取线程变量
     * @param key 键
     * @return 值
     */
    public static Object get(String key) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            return null;
        }
        return map.get(key);
    }

    /**
     * 清除租户信息
     */
    public static void clear() {
        threadLocal.remove();
    }
} 